package wechat

import (
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/iGoogle-ink/gopay/wechat"
)

var (
	instances   = gmap.NewStrAnyMap(true)
	DefaultName = "wechat"
)

func New(name string) *wechat.Client {
	config := g.Cfg().GetMapStrStr(name)
	if config == nil {
		panic("支付失败：支付配置有误")
	}

	// appId：应用ID
	// MchID：商户ID
	// apiKey：API秘钥值
	// isProd：是否是正式环境
	return wechat.NewClient(config["appId"], config["MchID"], config["apiKey"], gconv.Bool(config["isProd"]))
}

// 容器封装
func Instance(name ...string) *wechat.Client {
	key := DefaultName
	if len(name) > 0 && name[0] != "" {
		key = "payment.config." + name[0]
	} else {
		key = "payment.config." + key
	}
	return instances.GetOrSetFuncLock(key, func() interface{} {
		return New(key)
	}).(*wechat.Client)
}

// 客户端示例
func Client(name ...string) *wechat.Client {
	return Instance(name...)
}
